package handler

import (
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/slrun/callcenter/internal/model"
)

// StartRecording 开始录音
func (h *Handler) StartRecording(c *gin.Context) {
	var req struct {
		CallID       string             `json:"call_id" binding:"required"`
		AgentID      string             `json:"agent_id" binding:"required"`
		RecordingType model.RecordingType `json:"recording_type" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	recording, err := h.Services.RecordingService.StartRecording(req.CallID, req.AgentID, req.RecordingType)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, recording)
}

// StopRecording 停止录音
func (h *Handler) StopRecording(c *gin.Context) {
	callID := c.Param("call_id")
	if callID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "call_id is required"})
		return
	}

	recording, err := h.Services.RecordingService.StopRecording(callID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, recording)
}

// GetRecording 获取录音详情
func (h *Handler) GetRecording(c *gin.Context) {
	recordingID := c.Param("id")
	if recordingID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "recording id is required"})
		return
	}

	recording, err := h.Services.RecordingService.GetRecording(recordingID)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "recording not found"})
		return
	}

	c.JSON(http.StatusOK, recording)
}

// SearchRecordings 搜索录音
func (h *Handler) SearchRecordings(c *gin.Context) {
	var criteria model.RecordingSearchCriteria

	// 绑定查询参数
	criteria.AgentID = c.Query("agent_id")
	criteria.CustomerID = c.Query("customer_id")
	criteria.PhoneNumber = c.Query("phone_number")
	criteria.Direction = c.Query("direction")
	criteria.Status = c.Query("status")
	criteria.Type = c.Query("type")

	// 解析日期
	if startDateStr := c.Query("start_date"); startDateStr != "" {
		if startDate, err := time.Parse("2006-01-02", startDateStr); err == nil {
			criteria.StartDate = startDate
		}
	}

	if endDateStr := c.Query("end_date"); endDateStr != "" {
		if endDate, err := time.Parse("2006-01-02", endDateStr); err == nil {
			// 设置为当天结束时间
			criteria.EndDate = endDate.Add(24*time.Hour - time.Second)
		}
	}

	// 解析分页参数
	if pageStr := c.Query("page"); pageStr != "" {
		if page, err := strconv.Atoi(pageStr); err == nil {
			criteria.Page = page
		}
	}

	if pageSizeStr := c.Query("page_size"); pageSizeStr != "" {
		if pageSize, err := strconv.Atoi(pageSizeStr); err == nil {
			criteria.PageSize = pageSize
		}
	}

	// 解析时长参数
	if minDurationStr := c.Query("min_duration"); minDurationStr != "" {
		if minDuration, err := strconv.ParseInt(minDurationStr, 10, 64); err == nil {
			criteria.MinDuration = minDuration
		}
	}

	if maxDurationStr := c.Query("max_duration"); maxDurationStr != "" {
		if maxDuration, err := strconv.ParseInt(maxDurationStr, 10, 64); err == nil {
			criteria.MaxDuration = maxDuration
		}
	}

	recordings, total, err := h.Services.RecordingService.SearchRecordings(criteria)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"data":  recordings,
		"total": total,
		"page":  criteria.Page,
		"size":  criteria.PageSize,
	})
}

// DownloadRecording 下载录音
func (h *Handler) DownloadRecording(c *gin.Context) {
	recordingID := c.Param("id")
	if recordingID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "recording id is required"})
		return
	}

	// 获取录音文件
	data, fileName, err := h.Services.RecordingService.DownloadRecording(recordingID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 设置响应头
	c.Header("Content-Description", "File Transfer")
	c.Header("Content-Transfer-Encoding", "binary")
	c.Header("Content-Disposition", "attachment; filename="+fileName)
	c.Header("Content-Length", strconv.Itoa(len(data)))

	// 返回文件内容
	c.Data(http.StatusOK, "application/octet-stream", data)
}

// ArchiveRecording 归档录音
func (h *Handler) ArchiveRecording(c *gin.Context) {
	recordingID := c.Param("id")
	if recordingID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "recording id is required"})
		return
	}

	if err := h.Services.RecordingService.ArchiveRecording(recordingID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "recording archived successfully"})
}

// GetQualityTemplates 获取质检模板
func (h *Handler) GetQualityTemplates(c *gin.Context) {
	templates, err := h.Services.RecordingService.GetQualityTemplates()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, templates)
}

// CreateQualityTemplate 创建质检模板
func (h *Handler) CreateQualityTemplate(c *gin.Context) {
	var template model.QualityTemplate
	if err := c.ShouldBindJSON(&template); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.Services.RecordingService.CreateQualityTemplate(&template); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, template)
}

// AssignQualityCheckTask 分配质检任务
func (h *Handler) AssignQualityCheckTask(c *gin.Context) {
	var task model.QualityCheckTask
	if err := c.ShouldBindJSON(&task); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.Services.RecordingService.AssignQualityCheckTask(&task); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, task)
}

// SubmitQualityCheck 提交质检结果
func (h *Handler) SubmitQualityCheck(c *gin.Context) {
	var check model.QualityCheck
	if err := c.ShouldBindJSON(&check); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err := h.Services.RecordingService.SubmitQualityCheck(&check); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, check)
}